<script setup>
import { ref,getCurrentInstance,onMounted } from 'vue'
import {onLoad, onUnload} from '@dcloudio/uni-app'

const observer = ref(null);
const appear = ref(false);
const instance = ref(null);
onMounted(() => {
  instance.value = getCurrentInstance();
  console.log('onMounted',instance.value)

  observer.value = uni.createIntersectionObserver(instance.value);
  // 如果 .ball 出现在 .scroll-view 可视区域，则执行回调
  observer.value
      .relativeTo('.scroll-view') // 第二个参数 定义相交边界 left top right bottom
      .observe('.ball', (res) => {
    console.log('createIntersectionObserver res',res)
    // res.intersectionRatio 0-1 相交比例 大于0 小球出现
    if (res.intersectionRatio > 0 && !appear.value) {
      appear.value = true;
    } else if (!res.intersectionRatio > 0 && appear.value) {
      appear.value = false;
    }
  })
})
onUnload(() => {
  observer.value.disconnect();
})
</script>

<template>
  <view class="container">
    <text>{{ appear ? '小球出现' : '小球消失' }}</text>
    <view class="page-section">
      <scroll-view class="scroll-view" scroll-y>
        <view class="scroll-area">
          <text class="notice">向下滚动让小球出现</text>
          <view class="ball"></view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
}

.scroll-view {
  height: 400rpx;
  background: #fff;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.scroll-area {
  height: 1800rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: .5s;
}

.notice {
  margin: 150rpx 0 400rpx 0;
}

.ball {
  width: 200rpx;
  height: 200rpx;
  background: #1AAD19;
  border-radius: 50%;
}
</style>